package cn.restcloud.example.controller;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * 通过okhttp调用API服务示例
 * @author restcloud
 *
 */
public class DiscoveryClient{
		private static Gson gson = new GsonBuilder().create(); //null bean转json null值不输出
		private String host="http://47.107.60.192:8081/restcloud"; //注册中心服务器地址
		private String loginUrl=host+"/rest/core/auth/login"; //登录地址无需修改
		private String discoveryUrl=host+"/rest/discovery/heartbeat/update"; //服务注册的API地址
	    private String token=""; //登录成功后的token
	    private Date tokenCreatTime=null; //token的生成时间，超过一定时后用来重新刷新token
	    private int tokenExpiresNum=24; //24小时后重新刷新token
	    private String userId="admin"; //在API平台中注册的帐号
	    private String password="pass123"; //帐号的密码,可用md5进行加密一次

		public static void main(String[] args) throws Exception {
			DiscoveryClient discoveryClient=new DiscoveryClient();
			discoveryClient.registerServer();
		}
	
	    /**
	     * 注册服务器到注册中心,这个改成定时30秒调用一次本方法即可
	     * @param url
	     * @param postParamsMap
	     * @return
	     * @throws IOException
	     */
		public String registerServer() throws Exception {
			HashMap<String,String> postParamsMap=new HashMap<String,String>();
			postParamsMap.put("serverId", "MyServer01"); //服务器唯一id
			postParamsMap.put("serverIP", "192.168.1.1"); //服务器IP
			postParamsMap.put("serverPort", "8080"); //http端口
			postParamsMap.put("serviceBaseUrl", "http://192.168.1.1:8080/rest"); //API或url的根路径
			postParamsMap.put("serviceName", "OA"); //服务的实例名称，如果是集群时多个服务器之间的服务名称必须保持一致
			postParamsMap.put("serverClusterFlag", "OA"); //集群标识，如果是集群时多个服务器之间的集群时必须保持一致
			postParamsMap.put("serverSerialNum", "MyServer01"); //服务器的唯一序列号与服务器唯一id保持一致即可
			postParamsMap.put("serviceNum", "0"); //API数量
			postParamsMap.put("exceptionNum", "0"); //异常数量
			postParamsMap.put("weight", "10"); //服务器的权限1-10的数字
			postParamsMap.put("accessTotalCount", "0"); //API总调用次数
			postParamsMap.put("activeThreadCount", "0"); //当前线程数
			postParamsMap.put("state", "1"); //状态1表示有效，0表示停用
			postParamsMap.put("avgResponseTime", "0.01"); //平均响应时间秒
			
			
			//使用键值对的方式提交
			FormBody.Builder builder = new FormBody.Builder();
		    for (String key : postParamsMap.keySet()) {
		             builder.add(key, postParamsMap.get(key));//追加表单信息
		    }
		    RequestBody formBody = builder.build();
		    Request request = new Request.Builder().addHeader("identitytoken", this.token).url(this.discoveryUrl).post(formBody).build();
		    Response response = getOkHttpClient().newCall(request).execute();
		    String resultBody = response.body().string();
		    System.out.println(resultBody);
		    return resultBody;
		}
		
		public DiscoveryClient() {
			this.getToken(this.userId,this.password); //登录
		}
		
		public OkHttpClient getOkHttpClient() {
			 OkHttpClient client = new OkHttpClient();
			 return client;
		}
		
		/**
		 * 登录获取token
		 * @return
		 * @throws IOException
		 */
		public void getToken(String userId,String password){
			if(!this.token.equals("")) {
				//如果已经登录不再登录,要看token是否已经过期,如果已过期需要重新获取
				Date nowDate=new java.util.Date();
				Calendar specialDate = Calendar.getInstance();
		    	specialDate.setTime(nowDate);
		    	specialDate.add(Calendar.HOUR, -tokenExpiresNum); //当前时间往前推24小时
		    	Long between = (specialDate.getTime().getTime() - this.tokenCreatTime.getTime());
		    	if(between<0) { //如果往前推的时间小于token创建时间则在有效期内
		    		return;
		    	}
			}
			String tokenJson="";
			try {
				//使用键值对提交的方式
				Map<String,String> postParamsMap=new HashMap<String,String>();
				postParamsMap.put("userName", userId);
				postParamsMap.put("password", password);
				FormBody.Builder builder = new FormBody.Builder();
		        for (String key : postParamsMap.keySet()) {
		             builder.add(key, postParamsMap.get(key));//追加表单信息
		        }
		        RequestBody formBody = builder.build();
			    Request request = new Request.Builder().url(this.loginUrl).post(formBody).build();
			    Response response = getOkHttpClient().newCall(request).execute();
			    tokenJson=response.body().string();  //登录成功返回token
			    HashMap<String, String> tokenMap = gson.fromJson(tokenJson, new TypeToken<HashMap<String, String>>() {}.getType());
			    String state=tokenMap.get("state");
			    if(state!=null && state.equals("false")) {
			    	System.out.println("系统登录失败"+tokenJson);
			    }else {
			    	this.token=tokenMap.get("identitytoken");
			    	this.tokenCreatTime=new java.util.Date();
			    }
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		
}

